<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
    </style>
</head>
<body>
    <h4 class="mb-4">用户管理</h4>

    <div class="card">
        <div class="card-body">
            <div class="d-flex justify-content-between mb-3">
                <div class="input-group" style="width: 300px;">
                    <input type="text" id="searchName" class="form-control" placeholder="搜索用户名">
                    <button class="btn btn-outline-secondary" type="button" id="btnSearch">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                </div>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal" onclick="resetForm()">
                    <i class="bi bi-plus"></i> 新增用户
                </button>
            </div>
            
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>邮箱</th>
                            <th>备注</th>
                            <th>是否管理员</th>
                            <th>是否激活</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody">
                        <!-- 用户数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <nav aria-label="Page navigation" class="mt-3">
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 用户信息模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">用户信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId">
                        <div class="mb-3">
                            <label for="name" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="email" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="email">
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码</label>
                            <input type="password" class="form-control" id="password">
                            <div class="form-text" id="passwordHelpText">编辑时留空表示不修改密码</div>
                        </div>
                        <div class="mb-3">
                            <label for="remark" class="form-label">备注</label>
                            <textarea class="form-control" id="remark" rows="3"></textarea>
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="isAdmin">
                            <label class="form-check-label" for="isAdmin">是否管理员</label>
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="isActive">
                            <label class="form-check-label" for="isActive">是否激活</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="btnSaveUser">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 菜单权限模态框 -->
    <div class="modal fade" id="menuModal" tabindex="-1" aria-labelledby="menuModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="menuModalLabel">菜单权限</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="menuTreeContainer">
                        <!-- 菜单树将通过JavaScript动态加载 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="btnSaveMenus">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let currentUserId = null;
        let selectedMenuIds = [];
        
        // 页面加载完成后执行
        $(document).ready(function() {
            // 设置AJAX请求头部添加token
            $.ajaxSetup({
                beforeSend: function(xhr) {
                    const token = localStorage.getItem('token');
                    if (token) {
                        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        // 认证失败，可以通知父窗口处理
                        if (window.parent && window.parent.Auth) {
                            window.parent.Auth.logout();
                        }
                    }
                }
            });
            
            // 加载用户列表
            loadUsers();
            
            // 绑定搜索按钮事件
            $('#btnSearch').click(function() {
                currentPage = 1;
                loadUsers();
            });
            
            // 回车键搜索
            $('#searchName').keypress(function(e) {
                if (e.which === 13) {
                    currentPage = 1;
                    loadUsers();
                }
            });
            
            // 保存用户信息
            $('#btnSaveUser').click(saveUser);
            
            // 保存菜单权限
            $('#btnSaveMenus').click(saveMenus);
        });
        
        // 加载用户列表
        function loadUsers() {
            const searchName = $('#searchName').val();
            const skip = (currentPage - 1) * pageSize;
            
            $.ajax({
                url: `/admin/api/users?skip=${skip}&limit=${pageSize}&name=${searchName}`,
                type: 'GET',
                success: function(response) {
                    renderUserTable(response.items);
                    // 使用后端返回的分页信息
                    renderPagination(response.total, response.pages);
                },
                error: function(xhr) {
                    alert('加载用户列表失败: ' + xhr.responseJSON?.detail || '未知错误');
                }
            });
        }
        
        // 渲染用户表格
        function renderUserTable(users) {
            const tableBody = $('#userTableBody');
            tableBody.empty();
            
            if (users.length === 0) {
                tableBody.append(`<tr><td colspan="8" class="text-center">没有找到用户</td></tr>`);
                return;
            }
            
            users.forEach(user => {
                tableBody.append(`
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.name}</td>
                        <td>${user.email || '-'}</td>
                        <td>${user.remark || '-'}</td>
                        <td>${user.is_admin ? '是' : '否'}</td>
                        <td>${user.is_active ? '是' : '否'}</td>
                        <td>${new Date(user.created_at).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary me-1" onclick="editUser(${user.id})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-success me-1" onclick="editMenus(${user.id})">
                                <i class="bi bi-list-check"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    </tr>
                `);
            });
        }
        
        // 渲染分页
        function renderPagination(totalItems, totalPages) {
            const pagination = $('#pagination');
            pagination.empty();
            
            // 如果没有数据，不显示分页
            if (totalItems === 0) {
                return;
            }
            
            // 计算显示的页码范围（最多显示5页）
            let startPage = Math.max(currentPage - 2, 1);
            let endPage = Math.min(startPage + 4, totalPages);
            
            if (endPage - startPage < 4) {
                startPage = Math.max(endPage - 4, 1);
            }
            
            // 上一页
            pagination.append(`
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage - 1}); return false;">上一页</a>
                </li>
            `);
            
            // 第一页
            if (startPage > 1) {
                pagination.append(`
                    <li class="page-item">
                        <a class="page-link" href="#" onclick="changePage(1); return false;">1</a>
                    </li>
                `);
                
                // 省略号
                if (startPage > 2) {
                    pagination.append(`
                        <li class="page-item disabled">
                            <a class="page-link" href="#">...</a>
                        </li>
                    `);
                }
            }
            
            // 页码
            for (let i = startPage; i <= endPage; i++) {
                pagination.append(`
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>
                    </li>
                `);
            }
            
            // 最后一页
            if (endPage < totalPages) {
                // 省略号
                if (endPage < totalPages - 1) {
                    pagination.append(`
                        <li class="page-item disabled">
                            <a class="page-link" href="#">...</a>
                        </li>
                    `);
                }
                
                pagination.append(`
                    <li class="page-item">
                        <a class="page-link" href="#" onclick="changePage(${totalPages}); return false;">${totalPages}</a>
                    </li>
                `);
            }
            
            // 下一页
            pagination.append(`
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage + 1}); return false;">下一页</a>
                </li>
            `);
            
            // 显示总记录数和当前页信息
            pagination.append(`
                <li class="page-item disabled ms-2">
                    <a class="page-link" href="#">共 ${totalItems} 条记录，第 ${currentPage}/${totalPages} 页</a>
                </li>
            `);
        }
        
        // 切换页码
        function changePage(page) {
            if (page < 1) return;
            currentPage = page;
            loadUsers();
        }
        
        // 重置表单
        function resetForm() {
            $('#userId').val('');
            $('#userForm')[0].reset();
            $('#passwordHelpText').text('新增用户必须设置密码');
            $('#userModalLabel').text('新增用户');
            currentUserId = null;
        }
        
        // 编辑用户
        function editUser(id) {
            $.ajax({
                url: `/admin/api/users/${id}`,
                type: 'GET',
                success: function(user) {
                    currentUserId = user.id;
                    $('#userId').val(user.id);
                    $('#name').val(user.name);
                    $('#email').val(user.email || '');
                    $('#password').val('');
                    $('#passwordHelpText').text('留空表示不修改密码');
                    $('#remark').val(user.remark || '');
                    $('#isAdmin').prop('checked', user.is_admin === 1);
                    $('#isActive').prop('checked', user.is_active === 1);
                    
                    $('#userModalLabel').text('编辑用户');
                    $('#userModal').modal('show');
                },
                error: function(xhr) {
                    alert('获取用户信息失败: ' + xhr.responseJSON?.detail || '未知错误');
                }
            });
        }
        
        // 保存用户
        function saveUser() {
            const userData = {
                name: $('#name').val(),
                email: $('#email').val(),
                password: $('#password').val(),
                remark: $('#remark').val(),
                is_admin: $('#isAdmin').is(':checked') ? 1 : 0,
                is_active: $('#isActive').is(':checked') ? 1 : 0
            };
            
            // 如果是编辑模式且密码为空，则删除密码字段
            if (currentUserId && !userData.password) {
                delete userData.password;
            }
            
            if (currentUserId) {
                // 更新用户
                $.ajax({
                    url: `/admin/api/users/${currentUserId}`,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(response) {
                        $('#userModal').modal('hide');
                        loadUsers();
                    },
                    error: function(xhr) {
                        alert('更新用户失败: ' + xhr.responseJSON?.detail || '未知错误');
                    }
                });
            } else {
                // 新增用户
                if (!userData.password) {
                    alert('新增用户必须设置密码');
                    return;
                }
                
                $.ajax({
                    url: '/api/register',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(response) {
                        $('#userModal').modal('hide');
                        loadUsers();
                    },
                    error: function(xhr) {
                        alert('新增用户失败: ' + xhr.responseJSON?.detail || '未知错误');
                    }
                });
            }
        }
        
        // 删除用户
        function deleteUser(id) {
            if (!confirm('确定要删除此用户吗？')) return;
            
            $.ajax({
                url: `/admin/api/users/${id}`,
                type: 'DELETE',
                success: function(response) {
                    loadUsers();
                },
                error: function(xhr) {
                    alert('删除用户失败: ' + xhr.responseJSON?.detail || '未知错误');
                }
            });
        }
        
        // 编辑菜单权限
        function editMenus(id) {
            currentUserId = id;
            selectedMenuIds = [];
            
            $.ajax({
                url: `/admin/api/users/${id}/menus`,
                type: 'GET',
                success: function(response) {
                    const menuTree = response.menu_tree;
                    selectedMenuIds = response.user_menu_ids || [];
                    
                    renderMenuTree(menuTree);
                    $('#menuModal').modal('show');
                },
                error: function(xhr) {
                    alert('获取菜单权限失败: ' + xhr.responseJSON?.detail || '未知错误');
                }
            });
        }
        
        // 渲染菜单树
        function renderMenuTree(menuTree) {
            const container = $('#menuTreeContainer');
            container.empty();
            
            container.append('<ul class="list-group">');
            menuTree.forEach(menu => {
                renderMenuNode(menu, container);
            });
            container.append('</ul>');
        }
        
        // 渲染菜单节点
        function renderMenuNode(menu, parentContainer) {
            const isChecked = selectedMenuIds.includes(menu.id);
            
            const menuItem = $(`
                <li class="list-group-item">
                    <div class="form-check">
                        <input class="form-check-input menu-checkbox" type="checkbox" value="${menu.id}" id="menu-${menu.id}" ${isChecked ? 'checked' : ''}>
                        <label class="form-check-label" for="menu-${menu.id}">
                            ${menu.name} (${menu.code})
                        </label>
                    </div>
                </li>
            `);
            
            parentContainer.append(menuItem);
            
            if (menu.children && menu.children.length > 0) {
                const childContainer = $('<ul class="list-group ms-4"></ul>');
                menuItem.append(childContainer);
                
                menu.children.forEach(childMenu => {
                    renderMenuNode(childMenu, childContainer);
                });
            }
        }
        
        // 保存菜单权限
        function saveMenus() {
            const menuIds = [];
            $('.menu-checkbox:checked').each(function() {
                menuIds.push(Number($(this).val()));
            });
            
            $.ajax({
                url: `/admin/api/users/${currentUserId}/menus`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(menuIds),
                success: function(response) {
                    $('#menuModal').modal('hide');
                    alert('菜单权限已更新');
                },
                error: function(xhr) {
                    alert('保存菜单权限失败: ' + xhr.responseJSON?.detail || '未知错误');
                }
            });
        }
    </script>
</body>
</html> 